<?php

/**
 * Swift日本語文字化け対応版
 * @author long-nt
 */

class myMail extends Swift
{
	private $objSender;
	private $objRecipients;
	private $objMessage;

	public function initialize()
	{
		mb_language("Ja");
		mb_internal_encoding('UTF-8');

		$this->objMessage = new Swift_Message('', null, 'text/plain', '7bit', 'UTF-8');
		$this->objMessage->headers->setCharset('ISO-2022-JP');
		$this->objMessage->headers->setEncoding('7bit');
		$this->objRecipients = new Swift_RecipientList();
	}

	public function setBody($strBody)
	{
		//$strBody = mb_convert_encoding($strBody, 'ISO-2022-JP', 'UTF-8');
		$this->objMessage->setBody($strBody);
	}

	public function setSubject($strSubject)
	{
		//$strSubject = self::my_mb_encode_mimeheader($strSubject, 'ISO-2022-JP', 'B');
		$this->objMessage->setSubject($strSubject);
	}

	public function setFrom($strMail, $strFrom = null)
	{
		$this->objMessage->setFrom(new Swift_Address($strMail, self::my_mb_encode_mimeheader($strFrom, 'ISO-2022-JP', 'B')));
	}

	public function setSender($strMail, $strSender = null)
	{
		$this->objSender = new Swift_Address($strMail, mb_convert_encoding($strSender, 'ISO-2022-JP', 'UTF-8'));
	}

	public function addReplyTo($strMail)
	{
		$this->objMessage->setReplyTo($strMail);
	}

	public function addTo($strMail)
	{
		$this->objRecipients->addTo($strMail);
	}

	public function addBcc($strMail)
	{
		$this->objRecipients->addBcc($strMail);
	}

	public function addCc($strMail)
	{
		$this->objRecipients->addCc($strMail);
	}

	public function sendMail()
	{
		try {
			$this->send($this->objMessage, $this->objRecipients, $this->objSender);
		} catch (Exception $ex) {
			throw $ex;
		}
	}

	private static function my_mb_encode_mimeheader($strString, $strCharset, $strTransfer)
	{
		$pos       = 0;
		$split     = 36;
		$strResult = '';

		// after 36 single bytes characters, if then comes MB, it is broken
		while($pos < mb_strlen($strString, 'UTF-8'))
		{
			$output = mb_strimwidth($strString, $pos, $split, '', 'UTF-8');
			$pos += mb_strlen($output, 'UTF-8');
			// 2008/1/11 furumoto修正
			// $strResult .= (($strResult)? ' ' : '').mb_encode_mimeheader($output, $strCharset, $strTransfer);
			$strResult .= (($strResult)? '' : '').mb_encode_mimeheader($output, $strCharset, $strTransfer);
		}

		return $strResult;
	}
}
